package com.akujin.onemanga;


import java.util.zip.GZIPInputStream;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.RedirectHandler;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import android.util.Log;

public class HTTPHelp {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();

    private String ret;
    private Exception error;
    private String rURL;
    
    HttpResponse response = null;
    HttpPost httpPost = null;

    public void clearCookies() {

    	httpClient.getCookieStore().clear();

    }
    
    public String returnResult() {
    	return ret;
    }
    
    public Exception returnError() {
    	return error;
    }
    
    public String getRedirectURL() {
    	return rURL;
    }
    
    public Boolean getPage(String url, String referer, Boolean usegzip, Boolean htmlcheck) {
    	ret = null;
    	
    	//httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
    	httpClient.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
    	httpClient.getParams().setParameter("http.socket.timeout", new Integer(1000));
    	httpClient.getParams().setParameter("http.protocol.content-charset", "UTF-8");
    	
    	HttpGet httpGet = new HttpGet(url);
    	response = null;
	

    	httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3");
    	httpGet.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    	httpGet.setHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
    	httpGet.setHeader("Accept-Encoding", "gzip,deflate");
    	httpGet.setHeader("Referer", referer);
    	
    	int tryNumber = 0;
    	
    	while(tryNumber<5){
    		tryNumber++;
	    	try {
	    		if(!usegzip) {
		    		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		    		ret = httpClient.execute(httpGet,responseHandler);
	    		}
	    		else {
		    		// Manual GZIP Encoding Handler
		    		response = httpClient.execute(httpGet,localContext);
			     	GZIPInputStream gzip = new GZIPInputStream(response.getEntity().getContent());
			     	byte data[] = new byte[1024];
			     	StringBuffer s = new StringBuffer(data.length);
			        while(gzip.read(data, 0,data.length) != -1) {
			        	s.append(new String(data));
		    		}
		    		gzip.close();
		    		ret = s.toString();
	    		}
	    		
	    		
	    		//Make sure the entire HTML was downloaded (trys 5 times)
	    		if(htmlcheck) {
		    		if(ret.indexOf("<html") != -1 && ret.indexOf("</html>") != -1) {
		    			Log.v("OneManga","Success on try number " + String.valueOf(tryNumber) + "." + String.valueOf(ret.indexOf("<html")) + "," + String.valueOf(ret.indexOf("</html>")) );
		    			return true;
		    		}
		    		else {
		    			break;
		    		}
	    		}
	    		else {
	    			return true;
	    		}
	    	}
	    	catch(Exception e) {
	    		error = e;
	    		break;
	    	}
    	}
    	
    	return false;
    }
    
    public Boolean postPage(String url, String data) {

    	ret = null;

    	httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);

    	httpPost = new HttpPost(url);
    	response = null;	

    	httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3");
    	httpPost.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    	httpPost.setHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
    	httpPost.setHeader("Accept-Encoding", "gzip,deflate");
    	//httpGet.setHeader("Referer", "http://anidb.net/perl-bin/animedb.pl?show=main");

    	try {
    		response = httpClient.execute(httpPost,localContext);
    	
    		RedirectHandler rh = httpClient.getRedirectHandler();
    		rURL = rh.getLocationURI(response, localContext).toString();
    		
	     	GZIPInputStream gzip = new GZIPInputStream(response.getEntity().getContent());
	     	byte dat[] = new byte[1024];
	     	StringBuffer s = new StringBuffer(dat.length);
	        while(gzip.read(dat, 0,dat.length) != -1) {
	        	s.append(new String(dat));
    		}
    		gzip.close();
    		ret = s.toString();
    		return true;
    	}
    	catch(Exception e) {
    		error = e;
    		//System.out.println("HTTP : Exception : "+e);
    		return false;
    	}
    }
}
